package com.projectdemo.springbootdemo1.config;

import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 我的地域处理器
 *
 * @date 2024/11/8
 * @author zhangzw
 **/
public class MyLocaleResolver implements LocaleResolver {

    /**
     * 地域处理 根据请求地址中的语言，判断选择哪个地区
     *
     * @param request 请求
     * @return java.util.Locale data
     * @date 2024/11/8
     * @author zhangzw
     **/
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Locale locale = Locale.getDefault();
        String path = request.getRequestURI();
        String [] paths = path.split("/");
        if(path.indexOf("/")<0||paths.length==0){
            return locale;
        }
        String language = paths[1];
        if(!StringUtils.isEmpty(language)){
            if(language.indexOf("-")<0){
                return locale;
            }
            //zh-CN,en-US
            String [] args = language.split("-");
            //国家-地区
            locale = new Locale(args[0],args[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

